package test10;

import java.io.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Scanner;

/**
 * 2. 分析以下需求，并用代码实现
 1.定义学生类,包含姓名(String name),性别(String gender),年龄(int age)三个属性,生成空参有参构造,set和get方法,toString方法
 2.键盘录入6个学员信息(录入格式:张三,男,25),要求有两个相同的信息,将6个学员信息存入到ArrayList集合中
 3.将存有6个学员信息的ArrayList集合对象写入到D:\\StudentInfo.txt文件中
 4.读取D:\\StudentInfo.txt文件中的ArrayList对象并遍历打印
 5.对ArrayList集合中的6个学生对象进行去重,将去重后的结果利用PrintWriter流写入到E:\\StudentInfo.txt文件中(写入格式：张三-男-25)
 */
public class TestDemo02 {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        Scanner scanner = new Scanner(System.in);
        ArrayList<Student> list = new ArrayList<>();

        for (int i = 0; i < 6; i++) {
            System.out.println("请输入学生姓名：");
            String name = scanner.next();
            System.out.println("请输入学生性别：");
            String gender = scanner.next();
            System.out.println("请输入学生年龄：");
            int age = scanner.nextInt();
            Student student = new Student(name,gender,age);
            list.add(student);

        }

        //将ArrayList集合写入文件中：
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:\\StudentInfo.txt"));
        //将集合序列化：
        oos.writeObject(list);
        oos.close();


        //反序列化
        //将集合中的student读取出来，遍历打印：
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:\\StudentInfo.txt"));
        Object o = ois.readObject();
        ois.close();
        if (o instanceof ArrayList){
            ArrayList<Student> list1 = (ArrayList<Student>) o;

            //遍历打印：
            for (Student student : list1) {
                System.out.println(student);
            }


            //去重：
            HashSet<Student> set = new HashSet<>();
            for (int i = 0; i < list1.size(); i++) {
                set.add(list1.get(i));
            }


            //写入文件：
            PrintWriter pw = new PrintWriter(new FileWriter("D:\\StudentInfo.txt"));
            for (Student student : set) {
                pw.write(student.getName()+"-"+student.getGender()+"-"+student.getAge());
                pw.write("\r\n");
            }

            pw.close();
         }




    }
}
